package com.gxa.ssm251.controller;

import com.gxa.ssm251.exception.BusinessException;
import com.gxa.ssm251.pojo.Coupon;
import com.gxa.ssm251.pojo.CpScope;
import com.gxa.ssm251.pojo.RedeemCode;
import com.gxa.ssm251.pojo.User;
import com.gxa.ssm251.service.RedeemCodeService;
import com.gxa.ssm251.service.UserService;
import com.gxa.ssm251.util.JsonResult;
import com.gxa.ssm251.util.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.*;

/**
 * @author 舒空
 * //@CrossOrigin 解决跨域
 */
@RestController
@RequestMapping("/redeemCode")
@Api(value = "兑换码控制器", tags = "兑换码接口api")
@CrossOrigin//解决跨域

public class RedeemCodeController {

    @Resource
    private RedeemCodeService redeemCodeService;
    @Resource
    private UserService userService;

    private JsonResult jsonResult = null;

    @ApiOperation("删除兑换码")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "map",value = "json格式的兑换码id",paramType = "body")
    )
    @PostMapping("/delete")
    public JsonResult delete(@RequestBody Map<String, Object> map) {
        jsonResult = new JsonResult();
        Integer id = Integer.parseInt(map.get("id").toString());
        Integer delete = redeemCodeService.delete(id);
        if (delete>1){
            jsonResult.setCode("1");
            jsonResult.setMsg("删除成功");
        }else {
            jsonResult.setCode("0");
            jsonResult.setMsg("删除失败");
        }
        return jsonResult;
    }

    @ApiOperation(value = "发送兑换码")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "map", value = "json格式的兑换码对象", paramType = "body")
    )
    @PostMapping("/put")
    public JsonResult putRedeemCode(@RequestBody Map<String, Object> map) {
        jsonResult = new JsonResult();
        Integer rdcId = Integer.parseInt(map.get("id").toString());
        List<RedeemCode> redeemCodes = redeemCodeService.selectById(rdcId);
        Integer cpId = 0;
        String code = null;
        for (RedeemCode redeemCode : redeemCodes) {
            cpId = redeemCode.getCpId();
            code = redeemCode.getCode();
        }
        User user = userService.selectById(cpId);
        if (user != null) {
            jsonResult.setValue("userName", user.getName());
            String userPhone = map.get("userPhone").toString();
            if (user.getPhone().equals(userPhone)) {
                jsonResult.setCode("1");
                jsonResult.setMsg("成功");
                jsonResult.setValue("code", code);
            } else {
                jsonResult.setCode("0");
                jsonResult.setMsg("未找到该用户，请检测手机号！");
            }
        } else {
            jsonResult.setMsg("用户名不存在");
        }

        return jsonResult;
    }

    @ApiOperation(value = "修改兑换码")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "map", value = "json格式的兑换码对象", paramType = "body")
    )
    @PostMapping("/update")
    public JsonResult updateCoupon(@RequestBody Map<String, Object> map) {
        jsonResult = new JsonResult();
        Integer rdcId = Integer.valueOf(map.get("id").toString());
        List<RedeemCode> selectById = redeemCodeService.selectById(rdcId);
        if (selectById != null) {
            jsonResult.setCode("1");
            jsonResult.setData(selectById);
        }

        RedeemCode redeemCode = new RedeemCode();
        redeemCode.setId(rdcId);
        redeemCode.setName(map.get("name").toString());
        redeemCode.setStartTime(Date.valueOf(map.get("startTime").toString()));
        redeemCode.setEndTime(Date.valueOf(map.get("endTime").toString()));
        redeemCode.setNumber(Integer.valueOf(map.get("number").toString()));
        redeemCode.setPrice(Double.valueOf(map.get("price").toString()));
        Integer update = redeemCodeService.update(redeemCode);

        String scope = map.get("Scope").toString();
        List<String> list = new ArrayList<>();
        String[] split = scope.split(",");
        list = Arrays.asList(split);
        List<Integer> aList = new ArrayList<>();
        List<Integer> bList = new ArrayList<>();
        Integer i = 0;
        Integer cpScopeId = 0;
        for (String s : list) {
            i = Integer.parseInt(s);
            aList.add(i);
        }
        for (RedeemCode code : selectById) {
            for (CpScope cpScope : code.getScopeList()) {
                cpScopeId = cpScope.getId();
                bList.add(cpScopeId);
            }
        }

        Integer updateScope = 0;

        //误差解决如果使用范围未改变就不改变updateScope的值从而不影响返回修改的msg
        if (!aList.equals(bList)) {
            updateScope = redeemCodeService.updateScope(rdcId, list);
        }


        if (update > 0 || updateScope > 0) {
            jsonResult.setCode("1");
            jsonResult.setMsg("修改成功");
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("修改失败");
        }
        return jsonResult;
    }

    @ApiOperation("分页逆序兑换码全查询")
    @PostMapping("/selectAllByPage")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "map", value = "json格式的兑换码page和size",paramType = "body")
    )
    public JsonResult selectAllByPage(@RequestBody Map<String, Object> map) {
        jsonResult = new JsonResult();
        Integer page = Integer.parseInt(map.get("page").toString());
        Integer size = Integer.parseInt(map.get("size").toString());
        page = (page - 1) * size;
        List<RedeemCode> coupons = redeemCodeService.selectAllByPage(page, size);
        Integer selectRedeemCodeAll = redeemCodeService.selectRedeemCodeAll();

        jsonResult.setCode("1");
        jsonResult.setCount(selectRedeemCodeAll);
        jsonResult.setData(coupons);
        return jsonResult;
    }

    @ApiOperation(value = "兑换码添加接口")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "map", value = "json格式的兑换码对象",
                    paramType = "body")
    )
    @PostMapping("/add")
    public JsonResult addRedeemCode(@RequestBody Map<String, Object> map) {
        jsonResult = new JsonResult();
        int random = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;//[1000-9999)
        String encode = MD5Util.encode(String.valueOf(random));
        String substring = encode.substring(0, 8);
        RedeemCode redeemCode = new RedeemCode();
        redeemCode.setName(map.get("name").toString());
        redeemCode.setStartTime(Date.valueOf(map.get("startTime").toString()));
        redeemCode.setEndTime(Date.valueOf(map.get("endTime").toString()));
        redeemCode.setNumber(Integer.valueOf(map.get("number").toString()));
        redeemCode.setPrice(Double.valueOf(map.get("price").toString()));
        redeemCode.setCode(substring);
        redeemCode.setCpId((int) (Math.random() * (20 - 1 + 1)) + 1);
        Integer integer = null;
        try {
            integer = redeemCodeService.addRedeemCode(redeemCode);
            RedeemCode selectByName = redeemCodeService.selectByName(redeemCode.getName());
            String scope = map.get("Scope").toString();
            List<String> list = new ArrayList<>();
            String[] split = scope.split(",");
            list = Arrays.asList(split);
            Integer integer1 = redeemCodeService.addRcScope(selectByName.getId(), list);
            if (integer > 0 && integer1 > 0) {
                jsonResult.setCode("1");
                jsonResult.setMsg("添加成功");
            } else {
                jsonResult.setCode("0");
                jsonResult.setMsg("添加失败");
            }
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                jsonResult.setCode("0");
                jsonResult.setMsg(e.getMessage());
            } else {
                e.printStackTrace();
            }
        }

        return jsonResult;
    }

}
